package org.example.controller;

import org.apache.poi.xwpf.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SetWord {

    private static HashMap<String, String> placeholders = new HashMap<>();

    private static String fontFamily = "Arial";

    public static void main(String[] args) {
        // 加载AMM.txt中的键值对
        setPlaceholders();
        
//        // 打印加载的键值对
//        System.out.println("Loaded placeholders:");
//        placeholders.forEach((key, value) -> System.out.println(key + " -> " + value));

        String directoryPath = "C:\\Users\\SIM\\OneDrive\\EASA翻译\\实训工卡英文版"; // 要遍历的目录路径
        try {
            List<Path> docxFiles = findDocxFiles(directoryPath);
            for (int i = 0; i < docxFiles.size(); i++) {
                fontFamily= "Arial";
//            for (int i = 0; i < 1; i++) {
                Path docxFile = docxFiles.get(i);
                System.out.println("Found DOCX file: " + docxFile.getFileName());
                // 这里可以添加处理每个docx文件的代码
                try (InputStream inputStream = Files.newInputStream(docxFile)) {
                    XWPFDocument document = new XWPFDocument(inputStream);
                    //对表格内容格式化
                    String fileName = docxFile.getFileName().toString();
                    String substringed = fileName.substring(0, 2);
                    String substring = substringed +"-00";
                    String ata = placeholders.get(substring);
                    formmatTable(document,docxFile,ata);
                    setHeadAndFoot(document,docxFile,ata);
                    String wordPath = "C:\\Users\\SIM\\OneDrive\\EASA翻译\\工卡格式化"+"\\"+substringed+" "+ata+".docx";
                    FileOutputStream outputStream1 = new FileOutputStream(wordPath);
                    document.write(outputStream1);
                    outputStream1.close();
                    document.close();
                }
            }
        } catch (IOException e) {
            System.err.println("Error while traversing directory: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 设置文档的页眉和页脚
     * @param document
     * @param docxFile
     * @param ata
     */
    private static void setHeadAndFoot(XWPFDocument document, Path docxFile, String ata) {
        fontFamily = "Times New Roman";
        List<XWPFHeader> headers = document.getHeaderList();
        if (headers != null && !headers.isEmpty()) {
            for (XWPFHeader header : headers) {
                List<XWPFTable> tables = header.getTables();
                for (XWPFTable table : tables) {
                    XWPFTableRow row0 = table.getRows().get(0);
                    XWPFTableCell cell = row0.getCell(0);
                    resetText("A/C Type",cell);
                    setSizeTenWithoutBold( cell);
                    cell = row0.getCell(1);
                    resetText("ATA "+docxFile.getFileName().toString().substring(0,2)+"  "+ata,cell);
                    setSize14WithBold(cell);
                    cell = row0.getCell(2);
                    resetText("Work Card NO.",cell);
                    setSizeTenWithoutBold( cell);
                    XWPFTableRow row1 = table.getRows().get(1);
                    cell = row1.getCell(0);
                    resetText("DA42NG", cell);
                    setSize12WithoutBold(cell);
                    cell = row1.getCell(2);
                    setSize12WithoutBold(cell);
                }
            }
        }

        List<XWPFFooter> footerList = document.getFooterList();
        if (footerList != null && !footerList.isEmpty()) {
            //这里如何删除页脚的段落，然后重新添加文字为CETC Wuhu Diamond Aircraft Manufacturing Training Center.
            for (XWPFFooter xwpfFooter : footerList) {
                for (XWPFParagraph paragraph : xwpfFooter.getParagraphs()) {
                    System.out.println(paragraph.getText());
                }

            }
        }

    }

    private static void setSize14WithBold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(14);
                run.setBold(true);
            }
        }
    }

    private static void setSizeTenWithoutBold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(10);
                run.setBold(false);
            }
        }
    }

    private static void formmatTable(XWPFDocument document, Path docxFile,String ata) {
        XWPFTable table0 = document.getTables().get(0);
        // 设置表格宽度为17.99厘米，转换为百分比或点数
        int widthInTwips = (int)(17.99 * 1440 / 2.54); // 将厘米转换为twips (1厘米 = 1440/2.54 twips)
        table0.setWidth(String.valueOf(widthInTwips));
        table0.setTableAlignment(TableRowAlign.CENTER);
        XWPFTableCell cell = table0.getRows().get(0).getCell(0);
        setStyle(cell);

        //替换第一行的文字
        XWPFTableRow row1 = table0.getRows().get(1);
        //删除第一行第二列的文字
        cell = row1.getCell(2);
        resetText("Category",cell);

        for (XWPFTableCell tableCell : row1.getTableCells()) {
            setSize11Bold(tableCell);
        }

        cell = table0.getRow(2).getCell(1);
        resetText("/",cell);
        cell = table0.getRow(2).getCell(2);
        resetText("B1",cell);
        for (XWPFTableCell tableCell : table0.getRows().get(2).getTableCells()) {
            setSize11WithoutBold(tableCell);
        }

        cell = table0.getRows().get(3).getCell(4);
        resetText("Revision",cell);
        for (XWPFTableCell tableCell : table0.getRows().get(3).getTableCells()) {
            setSize11Bold(tableCell);
        }

        cell = table0.getRows().get(4).getCell(4);
        resetText("0",cell);
        for (XWPFTableCell tableCell : table0.getRows().get(4).getTableCells()) {
            setSize11WithoutBold(tableCell);
        }

        cell = table0.getRows().get(5).getCell(0);
        resetText("Prepared by/\n" +
                "Date",cell);
        cell = table0.getRows().get(5).getCell(1);
        resetText("Reviewed by/\n" +
                "Date",cell);
        cell = table0.getRows().get(5).getCell(2);
        resetText("Approved by/\n" + "Date",cell);
        for (XWPFTableCell tableCell : table0.getRows().get(5).getTableCells()) {
            setSize11Bold(tableCell);
        }

        cell = table0.getRows().get(7).getCell(0);
        resetText("subject",cell);
        setSize12Bold(cell);
        cell = table0.getRows().get(7).getCell(1);
        XWPFRun run = cell.addParagraph().createRun();
        run.setText(ata);
        //设置文字居中
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        }
        setSize16Bold(cell);
        setSize12Bold(table0.getRow(8).getCell(0));
        setSize12WithoutBold(table0.getRow(9).getCell(0));
        cell = table0.getRow(10).getCell(0);
        resetText("Reference Materials (Manuals)",cell);
        setSize12WithBold(cell);

        cell = table0.getRows().get(12).getCell(0);
        setFontFamliy(cell);
        cell = table0.getRows().get(13).getCell(0);
        setFontFamliy(cell);
                XWPFTable table1 = document.getTables().get(1);
        List<XWPFTableRow> rows = table1.getRows();
        XWPFTableCell cell1 = rows.get(1).getCell(1);
        resetText("Trainee's Signature/Date",cell1);
        setSize10WithoutBold(cell1);
        for (int i = 0; i < rows.size(); i++) {
            XWPFTableRow row = rows.get(i);
            if (row.getTableCells().size()==1) {
                setSize15Bold(row.getTableCells().get(0));
            } else if (row.getTableCells().size()==2) {
                for (XWPFTableCell tableCell : row.getTableCells()) {
                    setSize10WithoutBold(tableCell);
                }
            }
        }
    }

    private static void setFontFamliy(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
            }
        }
    }

    private static void setSize12WithBold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(12);
                run.setBold(true);
            }
        }
    }

    private static void setSize10WithoutBold(XWPFTableCell tableCell) {
        for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(10.5);
                run.setBold(false);
            }
        }
    }

    private static void setSize15Bold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(15);
                run.setBold(true);
            }
        }
    }

    private static void setSize12WithoutBold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(12);
                run.setBold(false);
            }
        }
    }

    private static void resetText(String  text,XWPFTableCell cell){
        int size = cell.getParagraphs().size();
        for (int i = 0; i < size; i++){
            cell.removeParagraph(0);
        }
        cell.addParagraph().createRun().setText(text);
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        }
    }

    private static void setSize16Bold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(16);
                run.setBold(true);
            }
        }
    }

    private static void setSize12Bold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontFamily(fontFamily);
                run.setFontSize(12);
                run.setBold(true);
            }
        }
    }

    private static void setSize11Bold(XWPFTableCell tableCell) {
        for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontSize(11);
                run.setBold(true);
                run.setFontFamily(fontFamily);
            }
        }
    }

    private static void setSize11WithoutBold(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontSize(11);
                run.setBold(false);
                run.setFontFamily(fontFamily);
            }
        }
    }

    private static void setStyle(XWPFTableCell cell) {
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                run.setFontSize(14);
                run.setBold(true);
                run.setFontFamily(fontFamily);
            }
        }
    }





    /**
     * 读取AMM.txt文件，每一行都是一个键值对
     * 空格之前的是key，后面的是value，存入placeholders
     */
    public static void setPlaceholders(){
        Path filePath = Paths.get("AMM.txt");
        try {
            List<String> lines = Files.readAllLines(filePath);
            for (String line : lines) {
                if (line.trim().isEmpty()) continue;
                
                // 查找第一个空格的位置
                int spaceIndex = line.indexOf(" ");
                if (spaceIndex > 0) {
                    String key = line.substring(0, spaceIndex);
                    String value = line.substring(spaceIndex + 1).trim();
                    placeholders.put(key, value);
                }
            }
            System.out.println("Loaded " + placeholders.size() + " placeholders from AMM.txt");
        } catch (IOException e) {
            System.err.println("Error reading AMM.txt file: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 查找指定目录中所有.docx文件
     * @param directoryPath 目录路径
     * @return 包含所有.docx文件路径的列表
     * @throws IOException 如果IO操作失败
     */
    public static List<Path> findDocxFiles(String directoryPath) throws IOException {
        Path dir = Paths.get(directoryPath);
        if (!Files.exists(dir)) {
            throw new IOException("Directory does not exist: " + directoryPath);
        }
        
        try (Stream<Path> stream = Files.walk(dir)) {
            return stream
                .filter(Files::isRegularFile)
                .filter(path -> path.toString().toLowerCase().endsWith(".docx"))
                .collect(Collectors.toList());
        }
    }
}
